package cn.itcast.web.shiro;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 自定义shiro过滤器。继承父类 AuthorizationFilter
 */
public class MyPermissionsFilter extends AuthorizationFilter {

	/**
	 * 判断是否具有某种权限
	 *      /company/** = perms["企业管理","部门管理"]
	 *      mappedValue ： 配置过滤器中，需要匹配的权限数组
	 * 返回值：
	 *  true：具有权限
	 *  false：没有权限
	 * 需求：对传入的权限数据，只需要满足其中一个权限，返回true即可
	 */
	protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object mappedValue) throws Exception {
		//1.获取配置的filter的参数，数据转型获取数组
		String [] perms = (String []) mappedValue;  //["企业管理","部门管理"]
		//2.获取subject
		Subject subject = getSubject(servletRequest, servletResponse);
		//3.循环判断权限，满足其一即可返回true
		if (perms != null && perms.length>0) {
			for (String perm : perms) {
				//判断权限
				if (subject.isPermitted(perm)) {
					return true;
				}
			}
			return false;
		}else{
			return true; //具有权限执行
		}
	}
}
